package org.apogee.mil.client.main.pages.trainee.widgets;

import org.apogee.mil.client.factories.ServerServiceFactory;
import org.apogee.mil.client.utils.Session;
import org.apogee.mil.client.widgets.MessageWidget;
import org.apogee.mil.shared.User;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class TraineeMessageWidget implements IsWidget {
	private MessageWidget message;
	private int trainerId = -1;
	private User currentUser;
	
	public TraineeMessageWidget(int trainerId) {
		message = new MessageWidget();
		this.trainerId = trainerId;
		
		this.currentUser = ServerServiceFactory.getUser(Session.getSessionId());
	}
	
	@Override
	public Widget asWidget() {
		ContentPanel cp = new ContentPanel();
		cp.setAutoWidth(true);
		cp.setAutoHeight(true);
		cp.setHeaderVisible(true);
		cp.setHeading("Send Message to Trainer");
		
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(message.asWidget());
		
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		cp.addButton(new Button("Send", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				if (trainerId == -1) return;
				
				String msg = message.getMessage();
				
				ServerServiceFactory.getTraineeService(currentUser).addMessage(trainerId, currentUser.getUserId(), msg, new AsyncCallback<Boolean>() {
					
					@Override
					public void onSuccess(Boolean result) {
						if (result == false) {
							MessageBox.alert("Error", "Unable to send message. Please try again", null);
							return;
						}
						
						Info.display("Success", "Message Sent Successfully");
						message.resetMessage();
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						MessageBox.alert("Error", "Unable to send message.\n" + caught.getMessage(), null);
						
					}
				});
				
			}
		}));
		
		cp.add(hp);
		
		return cp;
	}

}
